package com.lyz.interceptors;

import com.lyz.annotations.Auth;
import com.lyz.services.SessionService;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class AuthInterceptor<T> implements HandlerInterceptor {

    private final SessionService<T> sessionService;

    public AuthInterceptor(SessionService<T> sessionService) {
        this.sessionService = sessionService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod api = (HandlerMethod) handler;
        if (!api.hasMethodAnnotation(Auth.class) &&
                !api.getBeanType().isAnnotationPresent(Auth.class)) {
            return true;
        }
        Auth auth = api.getMethodAnnotation(Auth.class);
        if (Objects.isNull(auth)) {
            auth = api.getBeanType().getAnnotation(Auth.class);
        }
        String permission = auth.value();
        return sessionService.check(permission);
    }
}
